import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Form, Input, Button, message, Switch, Upload, Space, Tabs } from 'antd';
import { UploadOutlined, SaveOutlined } from '@ant-design/icons';
import { getMiniprogramConfig, updateMiniprogramConfig } from '@/services/miniprogram';
import { request } from 'umi';

const { TabPane } = Tabs;
const {TextArea} = Input;
// 使用从services导入的API函数

const MiniprogramConfig = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');

  // 获取配置信息
  const fetchConfig = async () => {
    try {
      setLoading(true);
      const res = await getMiniprogramConfig();
      if (res.success) {
        form.setFieldsValue(res.data || {});
      } else {
        message.error(res.message || '获取小程序配置失败');
      }
    } catch (error) {
      console.error('获取小程序配置出错:', error);
      message.error('获取小程序配置失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConfig();
  }, []);

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      values.notice_enabled = values.notice_enabled?1:0;
      const res = await updateMiniprogramConfig(values);
      if (res.success) {
        message.success('保存成功');
        // 重新获取配置，确保显示最新数据
        fetchConfig();
      } else {
        message.error(res.message || '保存失败');
      }
    } catch (error) {
      console.error('保存小程序配置出错:', error);
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 上传配置
  const uploadProps = {
    name: 'file',
    action: '/api/v1/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        // 设置表单字段值
        form.setFieldsValue({
          [info.file.fieldName]: info.file.response.data.url,
        });
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  return (
    <PageContainer>
      <Card loading={loading}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="基础配置" key="basic">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                isOpen: true,
              }}
            >
              <Form.Item
                name="app_id"
                label="AppID"
                rules={[{ required: true, message: '请输入小程序AppID' }]}
              >
                <Input placeholder="请输入小程序AppID" />
              </Form.Item>
              
              <Form.Item
                name="app_secret"
                label="AppSecret"
                rules={[{ required: true, message: '请输入小程序AppSecret' }]}
              >
                <Input.Password placeholder="请输入小程序AppSecret" />
              </Form.Item>
              
              <Form.Item
                name="name"
                label="小程序名称"
                rules={[{ required: true, message: '请输入小程序名称' }]}
              >
                <Input placeholder="请输入小程序名称" />
              </Form.Item>
              
              <Form.Item
                name="logo"
                label="小程序Logo"
              >
                <Input placeholder="请上传小程序Logo" addonAfter={
                  <Upload {...uploadProps} fieldName="logo">
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                } />
              </Form.Item>
              
              <Form.Item
                name="notice_enabled"
                label="是否开启公告"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
              
              <Form.Item
                name="notice_title"
                label="公告标题"
              >
                <Input placeholder="请输入公告标题" />
              </Form.Item>
              
              <Form.Item
                name="notice_content"
                label="公告内容"
              >
                <TextArea rows={4} placeholder="请输入公告内容" />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存配置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          
          <TabPane tab="支付配置" key="payment">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
              <Form.Item
                name="mch_id"
                label="商户号"
                rules={[{ required: false, message: '请输入商户号' }]}
              >
                <Input placeholder="请输入商户号" />
              </Form.Item>
              
              <Form.Item
                name="mch_key"
                label="API V3密钥"
                rules={[{ required: false, message: '请输入商户密钥' }]}
              >
                <Input placeholder="请输入商户密钥" />
              </Form.Item>
              <Form.Item
                name="cert_serial_no"
                label="支付证书序列号"
                rules={[{ required: false, message: '请输入商户密钥' }]}
              >
                <Input placeholder="请输入商户密钥" />
              </Form.Item>
              <Form.Item
                name="cert_file"
                label="Cert证书"
              >
                <Input placeholder="请上传支付证书" addonAfter={
                  <Upload 
                    name="file"
                    action="/api/v1/miniprogram/config/upload_cert"
                    data={{ type: 'cert_file' }}
                    headers={{
                      Authorization: `Bearer ${localStorage.getItem('token')}`,
                    }}
                    accept=".pem,.crt,.key,.p12,.pfx"
                    onChange={(info) => {
                      if (info.file.status === 'done') {
                        message.success(`${info.file.name} 上传成功`);
                        form.setFieldsValue({
                          cert_file: info.file.response.data.url,
                        });
                      } else if (info.file.status === 'error') {
                        message.error(`${info.file.name} 上传失败`);
                      }
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                } />
              </Form.Item>
              <Form.Item
                name="key_file"
                label="支付Key证书"
              >
                <Input placeholder="请上传支付证书" addonAfter={
                  <Upload 
                    name="file"
                    action="/api/v1/miniprogram/config/upload_cert"
                    data={{ type: 'key_file' }}
                    headers={{
                      Authorization: `Bearer ${localStorage.getItem('token')}`,
                    }}
                    accept=".pem,.crt,.key,.p12,.pfx"
                    onChange={(info) => {
                      if (info.file.status === 'done') {
                        message.success(`${info.file.name} 上传成功`);
                        form.setFieldsValue({
                          key_file: info.file.response.data.url,
                        });
                      } else if (info.file.status === 'error') {
                        message.error(`${info.file.name} 上传失败`);
                      }
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                } />
              </Form.Item>
              
              <Form.Item
                name="notify_url"
                label="支付回调地址"
                rules={[{ required: false, message: '请输入支付回调地址' }]}
              >
                <Input placeholder="请输入支付回调地址" />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存配置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          
          <TabPane tab="分享设置" key="share">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
              <Form.Item
                name="share_title"
                label="分享标题"
                rules={[{ required: false, message: '请输入分享标题' }]}
              >
                <Input placeholder="请输入分享标题" />
              </Form.Item>
              
              <Form.Item
                name="share_image"
                label="分享图片"
              >
                <Input placeholder="请上传分享图片" addonAfter={
                  <Upload {...uploadProps} fieldName="share_image">
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                } />
              </Form.Item>
              
              <Form.Item
                name="share_description"
                label="分享描述"
              >
                <TextArea rows={4} placeholder="请输入分享描述" />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存配置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          
          <TabPane tab="协议设置" key="agreement">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
              <Form.Item
                name="privacy_policy"
                label="隐私政策"
              >
                <TextArea rows={10} placeholder="请输入隐私政策内容" />
              </Form.Item>
              
              <Form.Item
                name="user_agreement"
                label="用户协议"
              >
                <TextArea rows={10} placeholder="请输入用户协议内容" />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存配置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          
          <TabPane tab="模板消息" key="template">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
              <Form.Item
                name="order_pay_template"
                label="订单支付成功通知"
              >
                <Input placeholder="请输入模板ID" />
              </Form.Item>
              
              <Form.Item
                name="order_ship_template"
                label="订单发货通知"
              >
                <Input placeholder="请输入模板ID" />
              </Form.Item>
              
              <Form.Item
                name="order_complete_template"
                label="订单完成通知"
              >
                <Input placeholder="请输入模板ID" />
              </Form.Item>
              
              <Form.Item
                name="coupon_template"
                label="优惠券到账通知"
              >
                <Input placeholder="请输入模板ID" />
              </Form.Item>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存配置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </PageContainer>
  );
};

export default MiniprogramConfig;